package core.util.logging;

import core.proto.Util;
import core.util.logging.constants.Action;
import core.util.logging.constants.Location;
import core.util.logging.screen.ScreenCapture;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Date;
import java.util.Hashtable;

import org.apache.commons.io.FilenameUtils;

import static app.constants.CollabVizConstants.*;

/**
 */
public class UserLogWriter {

	private static String userLogFolderPath;
	public static String timeStamp;

	private static final String LOG_FORMATTER = "%s,%s,%s,%s";

	private static BufferedWriter out;

	/**
	+ * Whether to capture screen shots. 
	 */	
	private static boolean screenCapFlag = false;

	static{
		try {
			userLogFolderPath = new File(LOG_FOLDER).getPath();
			String userLogFilePath = Util.generateLogFilePath(USER_LOG_FILE_NAME);

			out = new BufferedWriter( new FileWriter( userLogFilePath, false ) );

			Runtime.getRuntime().addShutdownHook(new Thread(){
				public void run(){
					try {
						out.close();
					} catch (IOException e) { /* ignore */ }
				}
			});
		} catch (IOException e) {
			throw new Error(e);
		}  
	}



	/**
	 * Toggles screen capture mode. 
	 * @param screenCap
	 */
	public static void setScreenCap( boolean screenCap ) {
		screenCapFlag = screenCap;
	}

	public static void log2( String objectAffected, Location uiArea, Object action ) {
		Date now = new Date(System.currentTimeMillis());
		timeStamp = Long.toString(System.currentTimeMillis());

		if( screenCapFlag ) {
			ScreenCapture.takeScreenShot( FilenameUtils.concat(userLogFolderPath, timeStamp ));
		}
		// Time, Action, Object, Area
		String line = String.format( LOG_FORMATTER, Util.formatDate(now), action.toString(), objectAffected, uiArea);
		try {
			synchronized(out){
				out.write( line );
				out.newLine();
				out.flush();
			}
			System.out.println( line );
		} catch( IOException e ) {
			e.printStackTrace();
		}
	}

	// Legacy version, referenced in some places in the code. 
	// Commented out to enable eventual refactoring of these areas of the code.  
	public static void log( String objectAffected, Location uiArea, Object action ) {
		/*
		Date now = new Date(System.currentTimeMillis());
		timeStamp = Long.toString(System.currentTimeMillis());

		if( screenCapFlag ) {
			ScreenCapture.takeScreenShot( FilenameUtils.concat(userLogFolderPath, timeStamp ));
		}
		// Time, Action, Object, Area
		String line = String.format( LOG_FORMATTER, Util.formatDate(now), action.toString(), objectAffected, uiArea);
		try {
			out.write( line );
			out.newLine();
			out.flush();
			//System.out.println( line );
		} catch( IOException e ) {
			e.printStackTrace();
		}
		 */	}
}
